package com.example.template.common.storage;

import com.example.template.common.storage.impl.*;
import com.example.template.common.config.SiteOptions;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @className: StorageFactory
 * @description:  文件存储工厂类 根据配置决定由哪个存储方案实现
 * @author: Kuangkeli
 * @date: 2024/01/22 11:00
 **/
@Component
public class StorageFactory implements InitializingBean {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private SiteOptions siteOptions;

    private Map<String, FileOperation> fileRepoMap = new HashMap<>();

    public boolean registry(String key, FileOperation fileOperation) {
        if (fileRepoMap.containsKey(key)) {
            return false;
        }
        fileRepoMap.put(key, fileOperation);
        return true;
    }

    public FileOperation get() {
        String scheme = siteOptions.getValue("storage_scheme");
        if (StringUtils.isBlank(scheme)) {
            scheme = "native";
        }
        return fileRepoMap.get(scheme);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        fileRepoMap.put("native", applicationContext.getBean(NativeStorageImpl.class));
        fileRepoMap.put("upyun", applicationContext.getBean(UpYunStorageImpl.class));
        fileRepoMap.put("aliyun", applicationContext.getBean(AliyunStorageImpl.class));
        fileRepoMap.put("hwyun", applicationContext.getBean(HwyunObsStorageImpl.class));
        fileRepoMap.put("qiniu", applicationContext.getBean(QiniuStorageImpl.class));
        fileRepoMap.put("minio",applicationContext.getBean(MinioStorageImpl.class));
    }
}
